#include "const/oPreDefine.h"
#include "platform/oCamera.h"
using namespace platform;

oCamera::oCamera():
_target(nullptr),
_view(CCDirector::sharedDirector()->getWinSize())
{ }

oCamera::~oCamera()
{
	CC_SAFE_RELEASE_NULL(_target);
}

void oCamera::setBoudary(const CCRect& var)
{
	_boudary = var;
}

void oCamera::setView(const CCSize& var)
{
	_view = var;
}

const CCRect& oCamera::getBoudary() const
{
	return _boudary;
}

void oCamera::setPosition(const CCPoint& var)
{
	const CCPoint& lastPos = CCNode::getPosition();
	if (lastPos != var)
	{
		if (moved != NULL)
		{
			moved(var.x - lastPos.x, var.y - lastPos.y);
		}
		CCNode::setPosition(var);
	}
}

oCamera* oCamera::node()
{
	oCamera* camera = new oCamera();
	camera->autorelease();
	return camera;
}

void oCamera::lockAt( CCNode* target )
{
	if (target)
	{
		if (_target)
		{
			_target->release();
		}
		target->retain();
		_target = target;
		this->scheduleUpdateWithPriority(1);
	}
	else
	{
		CC_SAFE_RELEASE_NULL(_target);
		this->unscheduleUpdate();
	}
}

CCAffineTransform oCamera::nodeToParentTransform()
{
	return CCAffineTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
}

void oCamera::update( ccTime dt )
{
	CCPoint pos(
		-_target->getPositionX() + _view.width * 0.5f,
		-_target->getPositionY() + _view.height * 0.5f);
	CCPoint to(-_boudary.getLeft(), -_boudary.getTop());
	CCPoint from(-_boudary.getRight()+_view.width, -_boudary.getBottom()+_view.height+_boudary.getTop());
	pos = ccpClamp(pos, from, to);
	this->setPosition(pos);
}
